package com.cloudfun.campusshare.controller;

import com.cloudfun.campusshare.common.constant.DevicePlatform;
import com.cloudfun.campusshare.common.constant.RedisKey;
import com.cloudfun.campusshare.common.constant.RoleType;
import com.cloudfun.campusshare.common.response.BaseResult;
import com.cloudfun.campusshare.common.response.BaseResultFactory;
import com.cloudfun.campusshare.common.security.AuthRequired;
import com.cloudfun.campusshare.entity.DeviceEntity;
import com.cloudfun.campusshare.repo.DeviceEntityRepo;
import com.cloudfun.campusshare.service.DeviceService;
import com.cloudfun.msglisten.RemoteBloomFilterService;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * Created by Huqin on 2020/4/3
 */
@Slf4j
@RestController
@RequestMapping("/v1/prod")
@AuthRequired(role = RoleType.ADMIN)
public class UpdateProdController {

    @Autowired
    private DeviceEntityRepo deviceEntityRepo;

    @Autowired
    private DeviceService deviceService;

    @Reference
    private RemoteBloomFilterService remoteBloomFilterService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("/syncOnline")
    public BaseResult<?> syncOnline() {
        List<DeviceEntity> deviceEntities = deviceEntityRepo.findByOnlineIsNullAndPlatform(DevicePlatform.UHOME);
        for (DeviceEntity deviceEntity : deviceEntities) {
            deviceService.syncOnlineStatus(deviceEntity);
        }
        return BaseResultFactory.produceSuccess();
    }

    @GetMapping("/syncImeiSet")
    public BaseResult<?> syncImeiSet() {
        log.info("开始同步imei集合");
        List<DeviceEntity> deviceEntities = Lists.newArrayList(deviceEntityRepo.findAll());
        for (DeviceEntity deviceEntity : deviceEntities) {
            remoteBloomFilterService.addImei(deviceEntity.getImei());
            stringRedisTemplate.opsForSet().add(RedisKey.IMEI_SET, deviceEntity.getImei());
            log.debug("同步imei: {}", deviceEntity.getImei());
        }
        log.info("同步imei集合结束，完成{}个imei同步", deviceEntities.size());
        return BaseResultFactory.produceSuccess();
    }

}
